package com.wonder.admin.controller;

import java.util.Arrays;

import com.wonder.framework.aws.service.AwsS3Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wonder.admin.domain.SysFile;
import com.wonder.admin.service.SysFileService;
import com.wonder.common.common.AjaxResult;
import com.wonder.common.config.WonderConfig;
import com.wonder.common.utils.file.FileUploadUtils;
import com.wonder.common.utils.file.FileUtils;
import com.wonder.common.utils.file.MimeTypeUtils;
import com.wonder.common.utils.file.OSSServiceUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@Api(tags = "文件上传")
public class UploadController {
	
	@Autowired
	private SysFileService sysFileService;
	
	@Autowired
	OSSServiceUtil ossServiceUtil;

	@Autowired
	AwsS3Service awsS3Service;
	
	 /**
     * 通用上传请求
     */
    @ApiOperation(value = "文件上传")
    @PostMapping("/Upload/upload")
    public AjaxResult<String> uploadFile(MultipartFile file,String upload_config_id) throws Exception
    {
        try
        {
        	 if (!file.isEmpty())
             {  
        		 String fileType=file.getContentType();
        		 String hd5="";
        		 //Check the file hash, if the same file existed, then return the file path.
        		 if(Arrays.asList(MimeTypeUtils.DEFAULT_ALLOWED_IMAGES).contains(fileType)) {
        		 hd5=FileUtils.getMd5(file);
        		 SysFile existedFile=sysFileService.getOne(new QueryWrapper<SysFile>().eq("hash", hd5));
        		 if(existedFile!=null) return AjaxResult.data(existedFile.getFilepath());
        		 }
        		 
        		 String imgUrl="";
				 String uploadType=WonderConfig.getUploadType();
        		 switch(uploadType){
        		 case "ali":
        			 imgUrl = ossServiceUtil.uploadAliyun(file); 
        			 break;
				 case "aws-s3":
					 imgUrl=awsS3Service.upload(file);
					 break;

        		 default:
        	            // 上传并返回新文件名称
        			 imgUrl= FileUploadUtils.upload( file);
        	             	          
        		 }
        		 
        		 if(Arrays.asList(MimeTypeUtils.DEFAULT_ALLOWED_IMAGES).contains(fileType)) {
			    		 SysFile newFile=new SysFile();
			    		 newFile.setFilepath(imgUrl).setHash(hd5);
			    		 sysFileService.save(newFile);
        		 }
 
                 return AjaxResult.data(imgUrl);
             }
             return AjaxResult.failed("system.uploadError");
        }
        catch (Exception e)
        {
            return AjaxResult.failed(e.getMessage());
        }
    }
	

}
